package com.breakfast.fun.adapter.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseListAdapter;
import com.breakfast.fun.common.CommonCart;
import com.breakfast.fun.dao.ProductCart;
import com.breakfast.fun.data.entity.home.Product;
import com.breakfast.fun.data.entity.home.Products;
import com.breakfast.fun.ui.home.gallery.GalleryProductActivity;
import com.breakfast.fun.ui.home.product.NormalProductActivity;
import com.breakfast.fun.util.DaoUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.view.widget.PurchaseButton;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.breakfast.fun.util.DaoUtil.getProductList;

/**
 * 普通分类产品适配器
 * Created by Administrator on 2016/9/7.
 */
public class NormalProductAdapter extends BaseListAdapter<Product> {


    private List<ProductCart> productCarts;

    private List<Products> productsList = new ArrayList<>();

    private CommonCart mCommonCart = new CommonCart();

    private Boolean isClickAble = true;

    public addClickListener mAddClick;

    public interface addClickListener {
        public void add(View view);
    }

    public void setAddClickListener(addClickListener addClick) {
        mAddClick = addClick;
    }

    public NormalProductAdapter(Context context, List<Product> list) {
        super(context, list);

        mCommonCart.init(context);
        productCarts = mCommonCart.productCartDao.loadAll();
        for (int i = 0; i < productCarts.size(); i++) {
            mCommonCart.totalPrice += productCarts.get(i).getTotalPrice();
            mCommonCart.totalNum += productCarts.get(i).getNum();
        }
        mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
        mCommonCart.event.setTotalNum(mCommonCart.totalNum);
        EventBus.getDefault().post(mCommonCart.event);
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_product, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Product data = getItem(i);
        imageUtil.loadUrlImage(data.getImage(), holder.ivItemProduct);

        List<ProductCart> productCarts = getProductList(data.getCategoryId(), data.getId(), NormalProductActivity.chooseDate);

        //如果数据库中有商品，就设置文本数量
        if (productCarts != null && productCarts.size() == 1) {
            holder.pbItemProductAdd.setTextNum(productCarts.get(0).getNum());
        } else {
            holder.pbItemProductAdd.setTextNum(0);
        }

        //添加的逻辑是，先判断数据库中是否有商品
        //如果没有的话，就新增一条记录
        //否则，更新这条记录
        holder.pbItemProductAdd.setOnShoppingClickListener(new PurchaseButton.ShoppingClickListener() {
            @Override
            public void onAddClick(int num) {

                if (!isClickAble) {
                    return;
                }

                ProductCart productCart = new ProductCart(null, data.getCategoryId(), data.getId(), NormalProductActivity.chooseDate);

                List<ProductCart> productCartList = getProductList(data.getCategoryId(), data.getId(), NormalProductActivity.chooseDate);

                if (productCartList.size() == 0) {
                    productCart.setNum(1);
                    productCart.setImage(data.getImage());
                    productCart.setProductId(data.getId());
                    productCart.setName(data.getName());
                    productCart.setProductId(data.getId());
                    productCart.setPrice(data.getPrice());
                    productCart.setProductClassId(data.getProductClassId());
                    productCart.setTotalPrice(data.getPrice());
                    mCommonCart.productCartDao.insert(productCart);
//                    holder.pbItemProductAdd.setText("1");
                } else {
                    productCartList.get(0).setNum(productCartList.get(0).getNum() + 1);
                    productCartList.get(0).setTotalPrice(productCartList.get(0).getPrice() * productCartList.get(0).getNum());
                    mCommonCart.productCartDao.update(productCartList.get(0));
                    holder.pbItemProductAdd.setTextNum(productCartList.get(0).getNum());
                }

//                if(!holder.tvItemProductCount.getText().equals("0")){
//                    holder.pbItemProductAdd.setTextNum(1);
//                }
                mCommonCart.totalNum += 1;
                mCommonCart.totalPrice += data.getPrice();
                mCommonCart.event.setTotalNum(mCommonCart.totalNum);
                mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
                EventBus.getDefault().post(mCommonCart.event);
                if (mAddClick != null) {
                    mAddClick.add(holder.pbItemProductAdd);
                }
                holder.pbItemProductAdd.clearAnimation();
            }

            @Override
            public void onMinusClick(int num) {

                if (!isClickAble) {
                    return;
                }

                List<ProductCart> productCartList = DaoUtil.getProductList(data.getCategoryId(), data.getId(), NormalProductActivity.chooseDate);
                productCartList.get(0).setNum(productCartList.get(0).getNum() - 1);
                productCartList.get(0).setTotalPrice(productCartList.get(0).getPrice()
                        * productCartList.get(0).getNum());
                mCommonCart.productCartDao.update(productCartList.get(0));
                if (holder.pbItemProductAdd.getTextNum() == 0) {
                    mCommonCart.productCartDao.delete(productCartList.get(0));
                }
                mCommonCart.totalNum -= 1;
                mCommonCart.totalPrice -= data.getPrice();
                mCommonCart.event.setTotalNum(mCommonCart.totalNum);
                mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
                EventBus.getDefault().post(mCommonCart.event);
            }
        });


        //删除的逻辑和增加的逻辑类似
        //如果更新记录后商品的数量变成0的话
        //就删除这条记录

        //点击商品时，进入商品详情图，这个有别于周套餐
        // 这个点击是只有一张详情图不可滑动的
        holder.ivItemProduct.setOnClickListener(v -> {


            Intent intent = new Intent(mContext,
                    GalleryProductActivity.class);
            Bundle bundle = new Bundle();
            //将当前List<Products>传到画廊
            for (Product p : mList) {
                Products products = new Products();
                products.setDate(NormalProductActivity.chooseDate);
                products.setProduct(p);
                products.setCategoryId(p.getCategoryId());
                productsList.add(products);
            }
            Products products = new Products();
            products.setDate(NormalProductActivity.chooseDate);
            products.setProduct(data);
            products.setCategoryId(data.getCategoryId());

            bundle.putSerializable("productLists", (Serializable) productsList);
            bundle.putSerializable("curProducts", (Serializable) products);            //当前选中的products
            if (TextUtils.isEmpty(data.getClosetime())) {
                bundle.putString("closeTime", "22:00:00");
            } else {
                bundle.putString("closeTime", data.getClosetime());
            }
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        });

        return convertView;
    }

    /**
     * 刷新底部弹出的购物车参数
     */
    public void refreshCartParam() {
        productCarts = DaoUtil.getProductCartDao().loadAll();
        mCommonCart.totalPrice = 0;
        mCommonCart.totalNum = 0;
        for (int i = 0; i < productCarts.size(); i++) {
            mCommonCart.totalPrice += productCarts.get(i).getTotalPrice();
            mCommonCart.totalNum += productCarts.get(i).getNum();
        }
    }

    public void setClickAble(Boolean clickAble) {
        isClickAble = clickAble;
    }

    static class ViewHolder {
        @Bind(R.id.iv_item_product)
        ImageView ivItemProduct;
        @Bind(R.id.pb_item_product_add)
        PurchaseButton pbItemProductAdd;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
